<template>
    <BasicModal 
      :width="950" 
      :minHeight="activeTab.id === TaskType.InstantTask ? 600: [TaskType.ScheduledTask, TaskType.ConditionalTask].includes(activeTab.id as number) ? 720: 820"
      :title="getModalTitle"
      okText="发布"
      wrapClassName="add-job-modal-wrap"
      @visible-change="handleVisibleChange"
      @register="register"
      @cancel="cancelModal"
      @ok="okModal"
    >
      <div class="container">
        <div class="tabs-wrap" :class="props.pageType === PageType.Edit && 'disabled'">
          <div class="tabs"
            :class="activeTab.id === item.id && 'active'"
            v-for="(item, index) in taskListTabs"
            @click="handleClickChange('tabs', item)"
            :key="index"
          >
            <img class="title-icon" :src="item.icon" />
            <div class="title">{{ item.name }}</div>
            <img class="active-icon" v-if="activeTab.id === item.id" :src="item.activeIcon" >
          </div>
        </div>
        <div class="form">
          <a-form
            ref="formRef"
            v-bind="formItemLayout"
            name="advanced_search"
            class="ant-advanced-search-form"
            :model="formState"
          >
            <a-row>
              <a-col :span="12">
                <a-form-item
                  label="任务名称"
                  name="jobName"
                  style="flex-direction: column; height: 60px;"
                  :labelCol="{ span: 12 }"
                  :wrapperCol="{ span: 22 }"
                  :rules="[{ required: true, message: '请输入任务名称' }]"
                >
                  <a-input v-model:value="formState.jobName" />
                </a-form-item>
                <a-form-item
                  label="执行设备"
                  name="deviceId"
                  style="flex-direction: column; height: 60px;"
                  :labelCol="{ span: 12 }"
                  :wrapperCol="{ span: 22 }"
                  :rules="[{ required: true, message: '请输入执行设备' }]"
                >
                  <a-select
                    v-model:value="formState.deviceId"
                    show-search
                    allowClear
                    style="width: 100%; height:100%; margin-top: 12px;"
                    placeholder="请输入执行设备"
                    :default-active-first-option="false"
                    :show-arrow="false"
                    :filter-option="false"
                    :not-found-content="null"
                    :options="deviceList"
                    @search="handleSearch"
                    @change="(value) => handleSelectChange('device', value)"
                  ></a-select>
                </a-form-item>
                <a-form-item :wrapperCol="{ span: 22 }">
                  <div class="device-info">
                    <div class="left">
                      <img :src="curDeviceRef?.deviceType ? mapViewImgUrl(`设备类型${curDeviceRef?.deviceType}`) : jobImgUrl('执行设备', 'svg')">
                    </div>
                    <div class="right">
                      <div class="title">{{ curDeviceRef?.deviceName || '' }}</div>
                      <div class="model">{{ curDeviceRef?.deviceModel || ''}}</div>
                      <div class="call-info">
                        <!-- <template v-if="curDeviceRef?.projectName"> -->
                          <span><img :src="mapViewImgUrl('部门')" /></span><span>{{ curDeviceRef?.projectName || ''}}</span>
                        <!-- </template> -->
                      </div>
                      <div class="call-info">
                          <span><img :src="mapViewImgUrl('电话')" /></span><span>{{ curDeviceRef?.contactPhone || ''}}</span>
                      </div>
                      <div class="call-info">
                          <span><img :src="mapViewImgUrl('人')" /></span><span>{{ curDeviceRef?.contactName || ''}}</span>
                      </div>
                    </div>
                  </div>
                </a-form-item>
                <a-form-item
                  label="失联动作"
                  name="lossAction"
                  :labelCol="{ span: 6 }"
                  :wrapperCol="{ span: 16 }"
                  :rules="[{ required: true, message: '请选择失联动作' }]"
                >
                  <a-select 
                    v-model:value="formState.lossAction" 
                    placeholder="请选择失联动作"
                    :options="lossActionOptions"
                  >
                  </a-select>
                </a-form-item>
                <a-form-item
                  label="自动断点续飞"
                  name="breakpoint"
                  :labelCol="{ span: 6 }"
                  :wrapperCol="{ span: 16, justify: 'end' }"
                  :rules="[{ required: true }]"
                >
                  <a-switch v-model:checked="formState.breakpoint" />
                </a-form-item>
              </a-col>
              <a-col :span="12">
                <a-form-item :wrapperCol="{ span: 24 }" style="margin-bottom: 5px;">
                  <a-row>
                    <a-col :span="11">
                      <a-form-item
                        label="执行航线"
                        name="wayLineId"
                        style="flex-direction: column; height: 60px;margin-bottom: 5px;"
                        :labelCol="{ span: 12 }"
                        :wrapperCol="{ span: 22 }"
                        :rules="[{ required: true, message: '请输入执行航线' }]"
                      >
                        <a-select
                          v-model:value="formState.wayLineId"
                          show-search
                          allowClear
                          style="width: 100%; margin-top: 5px;"
                          placeholder="请输入执行航线"
                          :default-active-first-option="false"
                          :show-arrow="false"
                          :filter-option="false"
                          :not-found-content="null"
                          :options="wayLineList"
                          @search="handleWayLineSearch"
                          @change="(value) => handleSelectChange('wayLine', value)"
                        ></a-select>
                      </a-form-item>
                    </a-col>
                    <a-col :span="13">
                      <div class="way-line-info">
                        <img :src="mapViewImgUrl('定位')">
                        <span style="margin-left: 5px;"><img :src="mapViewImgUrl('无人机')">{{ curWayLineRef?.droneModel || '未知无人机' }}</span>
                        <span style="margin-left: 5px;"><img :src="mapViewImgUrl('相机')">{{ curWayLineRef?.payloadModel||'未知相机' }}</span>
                      </div>
                    </a-col>
                  </a-row>
                </a-form-item> 
                <!--显示地图-->
                <a-form-item 
                  style="flex-direction: column; height: 339px;"
                >
                  <!--TODO: 地图画航线, 等待杨柳处理！-->
                  <div id="map-container"></div>
                  <!-- <template v-if="curWayLineRef?.fileObjectKey">
                    <div id="map-container"></div>
                  </template>
                  <template v-else>
                    <div class="map-container"><img  :src="jobImgUrl('执行航线', 'svg')"></div>
                  </template> -->
                </a-form-item>
                <a-form-item
                  label="完成动作"
                  name="finishAction"
                  :labelCol="{ span: 6 }"
                  :wrapperCol="{ span: 16 }"
                  :rules="[{ required: true, message: '请选择完成动作' }]"
                >
                  <a-select 
                    v-model:value="formState.finishAction" 
                    placeholder="请选择完成动作"
                    :options="finishActionOptions"
                  >
                  </a-select>
                </a-form-item>
                <a-form-item
                  label="相对机场返航高度"
                  name="alt"
                  :labelCol="{ span: 8 }"
                  :wrapperCol="{ span: 14 }"
                  :rules="[{ required: true, message: '请输入相对机场返航高度' }]"
                >
                  <a-input-number style="width: 100%;" min="20" max="1500" v-model:value="formState.alt" addon-after="m"></a-input-number>
                </a-form-item>
              </a-col>
            </a-row>
            <a-row style="margin: 10px 0px;" justify="space-around" v-if="[2, 3, 4].includes(activeTab.id as number)">
              <a-col :span="10"><div class="second-mod icon"><span class="task-icon"></span></div></a-col>
              <a-col :span="2"><div class="second-mod">{{ activeTab.name  }}</div></a-col>
              <a-col :span="10"><div class="second-mod icon"><span class="task-icon"></span></div></a-col>
            </a-row>
            <a-row v-if="[TaskType.ScheduledTask, TaskType.ConditionalTask, TaskType.RepeatingTask].includes(activeTab.id as number)" style="background: rgba(21,91,129,0.04)">
              <!--定时任务-->
              <template v-if="activeTab.id === TaskType.ScheduledTask">
                <a-col :span="12">
                  <a-form-item
                    label="执行时间"
                    :name="['jobTimeDto', 'time']"
                    style="flex-direction: column; height: 60px;"
                    :labelCol="{ span: 12 }"
                    :wrapperCol="{ span: 22 }"
                    :rules="[{ required: true, message: '请输入执行时间' }]"
                  >
                      <a-date-picker
                        style="width: 100%;"
                        v-model:value="formState.jobTimeDto.time"
                        showTime
                        format="YYYY-MM-DD HH:mm:ss"
                        value-format="YYYY-MM-DD HH:mm:ss"
                      />
                  </a-form-item>
                </a-col>
              </template>
              <!--重复任务-->
              <template v-if="activeTab.id === TaskType.RepeatingTask">
                <a-col :span="12">
                  <a-form-item
                    label="日期范围"
                    name="dateRange"
                    style="flex-direction: column; height: 60px;"
                    :labelCol="{ span: 12 }"
                    :wrapperCol="{ span: 22 }"
                    :rules="[{ required: true, message: '请输入日期范围' }]"
                  >
                      <a-range-picker style="width: 100%;" 
                        v-model:value="formState.dateRange" 
                        format="YYYY-MM-DD" 
                        value-format="YYYY-MM-DD"
                      />
                  </a-form-item>
                </a-col>
                <a-col :span="12">
                  <a-form-item
                    label="执行频率"
                    :name="['jobTimeDto', 'timeType']"
                    style="flex-direction: column; height: 60px;"
                    :labelCol="{ span: 12 }"
                    :wrapperCol="{ span: 22 }"
                    :rules="[{ required: true, message: '请选择执行频率' }]"
                  >
                    <a-select
                      style="width: 100%; margin-top: 5px;"
                      v-model:value="formState.jobTimeDto.timeType"
                      :options="timeTypeOptions"
                      @change="(value) => handleSelectChange('timeType', value)"
                    ></a-select>
                  </a-form-item>
                  <template v-if="formState.jobTimeDto.timeType == 2">
                    <a-form-item
                      :name="['jobTimeDto', 'weekDays']"
                      style="width: 100%;"
                      :wrapperCol="{ span: 22 }"
                      :rules="[{ required: true, message: '请选择' }]"
                    >
                        <div class="weekDayWrap" v-if="formState.jobTimeDto.timeType == 2">
                          <div
                            class="weekDayItem"
                            :class="formState.jobTimeDto.weekDays?.length && formState.jobTimeDto.weekDays.includes(item.value) && 'active'"
                            v-for="(item ,index) in weekOptions"
                            @click="handleClickChange('weekDays', item)"
                            :key="index"
                          >
                            {{  item.label }}
                          </div>
                        </div>
                    </a-form-item>
                  </template>
                  <a-form-item
                    label="执行时间"
                    :name="['jobTimeDto', 'time']"
                    style="flex-direction: column; height: 60px;"
                    :labelCol="{ span: 12 }"
                    :wrapperCol="{ span: 22 }"
                    :rules="[{ required: true, message: '请选择执行时间' }]"
                  >
                      <a-time-picker
                        style="width: 100%;" 
                        v-model:value="formState.jobTimeDto.time"
                        format="HH:mm:ss"
                        value-format="HH:mm:ss"
                      />
                  </a-form-item>
                </a-col>
              </template>
              <!--条件任务-->
              <template v-if="activeTab.id === TaskType.ConditionalTask">
                <a-col :span="12">
                  <a-form-item
                    label="执行条件"
                    style="flex-direction: column; height: 60px;"
                    :labelCol="{ span: 12 }"
                    :wrapperCol="{ span: 23 }"
                    :rules="[{ required: true }]"
                  >
                    <a-row style="height: 30px;">
                      <a-col :span="2" style="display: flex; justify-content: center; margin-top: 8px;">当</a-col>
                      <a-col :span="9">
                        <a-form-item
                          :name="['jobConditionDto', 'conditionId']"
                          style="margin-bottom: 0px;"
                          :rules="[{ required: true, message: '请选择条件' }]"
                        >
                          <a-select
                            style="width: 100%; margin-top: 5px;"
                            v-model:value="formState.jobConditionDto.conditionId"
                            :options="conditionList"
                            @change="(value) => handleSelectChange('conditionId', value)"
                          ></a-select>
                        </a-form-item>
                      </a-col>
                      <a-col :span="9">
                        <a-form-item
                          :name="['jobConditionDto', 'triggerValue']"
                          style="margin-bottom: 0px;"
                          :rules="[{ required: true, message: '请选择条件的取值' }]"
                        >
                          <a-select
                            style="width: 100%; margin-top: 5px;"
                            v-model:value="formState.jobConditionDto.triggerValue"
                            :options="valueInfoList"
                          ></a-select>
                        </a-form-item>
                      </a-col>
                      <a-col :span="4" style="display: flex; justify-content: center; margin-top: 8px;">触发任务</a-col>
                    </a-row>
                  </a-form-item>
                </a-col>
                <a-col :span="12">
                  <a-form-item
                    label="日期范围"
                    name="dateRange"
                    style="flex-direction: column; height: 60px;"
                    :labelCol="{ span: 12 }"
                    :wrapperCol="{ span: 22 }"
                    :rules="[{ required: true, message: '请输入日期范围' }]"
                  >
                      <a-range-picker style="width: 100%;" 
                        v-model:value="formState.dateRange" 
                        format="YYYY-MM-DD" 
                        value-format="YYYY-MM-DD"
                      />
                  </a-form-item>
                </a-col>
              </template>
            </a-row>
          </a-form>
        </div>
      </div>
    </BasicModal>
  </template>
  <script lang="ts" setup>
  import { inject, onMounted, computed, defineProps, watch, ref, reactive, defineEmits } from 'vue';
  import { BasicModal, useModalInner } from '/@/components/Modal';
  import ApiListOptions from '/@/api/type'
  import { deviceApi } from '/@/views/equipManage/deviceManageList/data.api'
  import { waylineApi } from '/@/views/wayline/data.api'
  import type { SelectProps } from 'ant-design-vue'
  import { useMessage } from '/@/hooks/web/useMessage';
  import AMapLoader from '@amap/amap-jsapi-loader';
  import { getIconUrl } from '/@/utils'
  import { PageType, TaskType } from '/@/constants/job'

  interface TabsItem {
    id: number
    name: string
    icon: string
    activeIcon: string
  }

  interface FormState {
    jobName: string;
    jobType: number;
    deviceId: string;
    deviceName: string;
    lossAction: number;
    breakpoint: boolean;
    wayLineId: string;
    wayLineName: string;
    finishAction: number;
    alt: number | null;
    conditionId: number | null;
    conditionValue: number | null;
    dateRange: any[];
    jobTimeDto: any;
    jobConditionDto: any;
  }

  const props = defineProps({
    pageType: {
      type: String,
      default: PageType.Add
    },
    jobData: {  // 复制和编辑时的数据
      
    }
  });

  const pageTypeList: any[] = [{
    type: PageType.Add,
    modalTitle: '新增任务'
  },{
    type: PageType.COPY,
    modalTitle: '复制任务'
  },{
    type: PageType.Edit,
    modalTitle: '编辑任务'
  }]

  const mapViewImgUrl = (name: string, suffix = 'svg') => {
    return `/mapView/${name}.${suffix}` //拼接文件路径
  }

  const jobImgUrl = (name: string, suffix = 'png') => {
    return getIconUrl(name, 'icons/job/', suffix)
  }

  const taskListTabs: TabsItem[] = [{
      id: TaskType.InstantTask,
      name: '即时任务',
      icon: jobImgUrl('即时任务'),
      activeIcon: jobImgUrl('对勾', 'svg')
    },{
      id: TaskType.ScheduledTask,
      name: '定时任务',
      icon: jobImgUrl('定时任务'),
      activeIcon: jobImgUrl('对勾', 'svg')
    },{
      id: TaskType.RepeatingTask,
      name: '重复任务',
      icon: jobImgUrl('重复任务'),
      activeIcon: jobImgUrl('对勾', 'svg')
    },
    {
      id: TaskType.ConditionalTask,
      name: '条件任务',
      icon: jobImgUrl('条件任务'),
      activeIcon: jobImgUrl('对勾', 'svg')
    },
  ]

  const lossActionOptions = ref<SelectProps['options']>([
    {
      value: 1,
      label: '立即返航',
    }
  ]);

  const finishActionOptions = ref<SelectProps['options']>([
    {
      value: 1,
      label: '自动返航',
    }
  ]);

  const timeTypeOptions = ref<SelectProps['options']>([
    {
      value: 1,
      label: '每天',
    },
    {
      value: 2,
      label: '每周',
    },
  ]);

  const weekOptions = ref<SelectProps['options']>([
    {
      value: 1,
      label: '周一',
    },
    {
      value: 2,
      label: '周二',
    },
    {
      value: 3,
      label: '周三',
    },
    {
      value: 4,
      label: '周四',
    },
    {
      value: 5,
      label: '周五',
    },
    {
      value: 6,
      label: '周六',
    },
    {
      value: 7,
      label: '周日',
    },
  ]);

  const formItemLayout = {
    labelAlign: 'left',
    labelCol: {
      xs: { span: 24 },
      sm: { span: 6 },
    },
    wrapperCol: {
      xs: { span: 24 },
      sm: { span: 16 },
    },
  };
  const baseFormState: FormState = {
    jobName: '',
    jobType: TaskType.InstantTask,
    deviceId: '',
    deviceName: '', 
    lossAction: 1,
    breakpoint: false,
    wayLineId: '',
    wayLineName: '',
    finishAction: 1,
    alt: null,
    conditionId: null, // 条件ID
    conditionValue: null,  // 条件的取值
    dateRange: [],   // 日期范围
    jobTimeDto: {  // 第2个模块参数
      timeType: 1,      // 执行频率(默认每天)
      weekDays: [],   // 每周设置的 第几星期
      time: ''       // 执行时间
    },
    jobConditionDto: {
      conditionId: '',
      triggerValue: ''
    }
  }
  const $http: ApiListOptions | undefined = inject('api')
  const [register, { closeModal }] = useModalInner();
  const emits = defineEmits(['success', 'register']);
  let map = ref(); // 高德地图实例对象
  let AmapObj = reactive<any>({})  // 高德地图实例对象
  const activeTab = reactive<Partial<TabsItem>>({})
  const formRef = ref()
  const formState = ref<FormState>({...baseFormState});
  let timeout: any = null;
  const currentValue = ref();
  const deviceList = ref<any[]>([])  // 设备列表
  const curDeviceRef = ref<any>(null);   // 选中的设备
  let timeoutWayLine: any = null;
  const currentValueWayLine = ref();
  const wayLineList = ref<any[]>([])  // 航线列表
  const curWayLineRef = ref<any>(null);   // 选中的航线
  const conditionList = ref<any[]>([])  // 条件列表
  const curConditionRef = ref<any>(null);   // 选中的条件
  const valueInfoList = ref<any[]>([])  // 条件列表的取值
  //const curValueInfoRef = ref<any>(null);   // 选中的条件取值

  const getModalTitle = computed((): string =>
    props.pageType ? pageTypeList.find(item => item.type === props.pageType).modalTitle : '新增任务'
  )

  watch(
    () => formState.value.jobType,
    async (newValue) => {
      //console.log("更新formState.jobType--", newValue, conditionList.value)
      if(newValue === TaskType.ConditionalTask && !conditionList.value?.length){
        initCondition()
      }
    }, { immediate:true }
  );

  const handleVisibleChange = async (visible) => {
    if(visible){
      //console.log("接受props", props)
      if([PageType.Edit, PageType.COPY].includes(props.pageType)){
        const { jobType, beginTime, endTime, jobConditionDto = {} } = props.jobData
        formState.value = props.jobData as FormState
        formState.value.dateRange = [beginTime, endTime]
        formState.value.jobConditionDto = jobConditionDto  // 返回可能为null
        activeTab.id = jobType
        activeTab.name = taskListTabs.find(item => item.id ===activeTab.id)?.name || ''
        await initMap()
        await asyncInit(props.jobData)
        if(jobType === TaskType.ConditionalTask && jobConditionDto?.conditionId){  // 异步更新条件
          await initCondition({ id: jobConditionDto?.conditionId })
        }
      }else{
        formState.value = {...baseFormState}
        formState.value.jobTimeDto = baseFormState.jobTimeDto
        await initMap()
        await initData()
      }
    }
  }

  // 异步更新设备/航线
  const asyncInit = async (data) => {
    const result = await $http?.getDeviceGet({ 
      deviceId: data.deviceId
    })
    if( result ) {
      curDeviceRef.value = result
    }
    formState.value.wayLineId = data.wayLineId.toString()
    handleWayLineSearch(data.wayLineName)
    const waylineRes = await waylineApi.get({
        waylineId: data.wayLineId,
        workspaceId: localStorage.getItem('Project_Id')
    })
    //console.log("waylineRes", waylineRes)
    if( waylineRes ) {
      curWayLineRef.value = waylineRes
    }
  }

  const initCondition = async (params = {}) => {
    const conditionRes  = await $http?.getConditionList({
      pageNo: 1,
      pageSize: 100,
      ...params
    })
    if( conditionRes.records?.length ) {
      const resData: any[] = conditionRes.records.map((item, index) => {
        return {
          ...item,
          value: item.id,
          label: item.conName,
        }
      });
      conditionList.value = resData
    }
  }
  
  // 初始化设备/航线/条件
  const initData = async () => {
    activeTab.id = TaskType.InstantTask
    activeTab.name = '即时任务'
    const result = await deviceApi.list({
      deviceType: '3',
      pageNo: 1,
      pageSize: 200
    })
    const { records = [] } = result
    if( records?.length ) {
      const resData: any[] = records.map((item, index) => {
        return {
          ...item,
          value: item.deviceId,
          label: item.deviceName,
        }
      });
      deviceList.value = resData
    }
    const waylineRes  = await waylineApi.query({
      pageNo: 1,
      pageSize: 200
    })
    if( waylineRes.records?.length ) {
      const resData: any[] = waylineRes.records.map((item, index) => {
        return {
          ...item,
          value: item.id,
          label: item.name,
        }
      });
      wayLineList.value = resData
    }
  }

  const initMap = async () => {
    try{
      const AMap = await AMapLoader.load({
        "key": "59c61f064c552f2ace25ff0c1d6465a7",  // 申请好的Web端开发者Key，首次调用 load 时必填
        "version": "2.0",   // 指定要加载的 JS API 的版本，缺省时默认为 1.4.15
        "plugins": [],      // 需要使用的的插件列表，如比例尺'AMap.Scale'等
      })
      AmapObj = AMap
      //console.log("加载完地图---------------")
      map.value = new AMap.Map('map-container', {
          center: [114.118725, 22.697947],
          zoom: 16,
          viewMode: '3D',//使用3D视图
      })
    }catch(e){
      console.log(e)
    }
  }

  //更新地图
  const handleChangeMap = (lng, lat) => {
    //console.log("更新地图==map", AmapObj, map.value)
    if(lng && lat){
      const position = new AmapObj.LngLat(lng, lat)
      map.value.setZoomAndCenter(16, position) // 传入经纬度，设置地图中心点
    }else{
      map.value.clearMap();
    }
  }

  const handleSelectChange = (type: string, value) => {
    //console.log("handleSelectChange==value", value)
    switch(type){
      case 'timeType':
        {
          if(value === 1) {
            formState.value.jobTimeDto.weekDays = []
          }
        }
      break;
      case 'device':
        {
          if(value){
            curDeviceRef.value =  deviceList.value.find(item => item.deviceId === value) // 缓存选中设备
            //console.log("curDeviceRef.value", curDeviceRef.value)
          }else{
            curDeviceRef.value =  null
          }
        }
      break;
      case 'wayLine':
        {
          if(value){
            curWayLineRef.value =  wayLineList.value.find(item => item.id === value)
            //console.log("curWayLineRef.value", curWayLineRef.value)
          }else{
            curWayLineRef.value = null
          }
        }
      break;
      case 'conditionId':
        {
          if(value){
            curConditionRef.value =  conditionList.value.find(item => item.id === value)
            valueInfoList.value = curConditionRef.value.valueInfo?.length ? curConditionRef.value.valueInfo.map(item => {
              return {
                value: item,
                label: item,
                key: Date.now()
              }
            }) : []
            //console.log("curConditionRef.value", curConditionRef.value)
          }else{
            curConditionRef.value = null
          }
        }
      break;
    }
  }

  const handleClickChange = (type: string, item) => {
    //console.log("handleClickChange==item", item)
    switch(type){
      case 'tabs':
        {
          const { id, name } = item
          activeTab.name = name
          activeTab.id = id
          formState.value.jobType = id
          formState.value.jobTimeDto = {
            timeType: 1,
            weekDays: [],
            time: ''
          }
          formState.value.jobConditionDto = {
            conditionId: '',
            triggerValue: ''
          }
        }
      break;
      case 'weekDays':
        {
          if(!formState.value.jobTimeDto.weekDays?.length){
            formState.value.jobTimeDto.weekDays = []
            formState.value.jobTimeDto.weekDays.push(item.value)
          }else{
            const index = formState.value.jobTimeDto.weekDays.findIndex( items => items == item.value)
            console.log("index", index, item.value, formState.value.jobTimeDto.weekDays)
            if(index !== -1){
              formState.value.jobTimeDto.weekDays.splice(index, 1)
            }else{
              formState.value.jobTimeDto.weekDays.push(item.value)
            }
          }
        }
      break;   
    }
  }

  const searchDeviceData = (value: string, callback: any) => {
    if (timeout) {
      clearTimeout(timeout);
      timeout = null;
    }

    currentValue.value = value;
    
    const fetch = async() => {
      const result = await deviceApi.list({ 
        deviceType: '3',
        deviceName: value,
        pageNo: 1,
        pageSize: 20
      })
      //console.log("result===", result)
      const { records = [] } = result
      if( records?.length ) {
        if (currentValue.value === value) {
          const resData: any[] = records.map((item, index) => {
            return {
              ...item,
              value: item.deviceId,
              label: item.deviceName,
            }
          });
          callback(resData);
        }
      }
    }
    timeout = setTimeout(fetch, 300)
  }

  const handleSearch = (val: any) => {
    //console.log("handleSearch--data", val)
    if(val){
      searchDeviceData(val, (d: any[]) => (deviceList.value = d));
    }
  };

  const searchWayLineData = (value: string, callback: any) => {
    if (timeoutWayLine) {
      clearTimeout(timeoutWayLine);
      timeoutWayLine = null;
    }

    currentValueWayLine.value = value;
    
    const fetch = async() => {
      const result = await waylineApi.query({ 
        name: value,
        pageNo: 1,
        pageSize: 20
      })
      //console.log("result===", result)
      const { records = [] } = result
      if( records?.length ) {
        if (currentValueWayLine.value === value) {
          const resData: any[] = records.map((item, index) => {
            return {
              ...item,
              value: item.id,
              label: item.name,
            }
          });
          callback(resData);
        }
      }
    }
    timeoutWayLine = setTimeout(fetch, 300)
  }

  const handleWayLineSearch = (val: any) => {
    //console.log("handleSearchWayLine--data", val)
    if(val){
      searchWayLineData(val, (d: any[]) => (wayLineList.value = d));
    }
  }

  const okModal = () => {
    formRef.value.validate().then(async(formResult) => {
      const { dateRange, jobTimeDto } = formState.value
      if(jobTimeDto){
        jobTimeDto.timeType = Number(jobTimeDto.timeType)
      }
      const formData: any = Object.assign({} , {
        ...formState.value,
        lossAction: Number(formState.value.lossAction),
        finishAction: Number(formState.value.finishAction),
        jobTimeDto: jobTimeDto
      })
      if(dateRange?.length){
        formData.beginTime = dateRange[0]
        formData.endTime = dateRange[1]
        formData.dateRange = undefined
      }
      if(props.pageType === PageType.COPY){
        formData.id = undefined
        formData.jobId = undefined
      }
      //console.log("表单校验--通过", formData)
      if([PageType.Add, PageType.COPY].includes(props.pageType)){
        const res = await $http?.postWaylinejobSave({ ...formData })
        const { data } = res
        if(data.code === 200){
          cancelModal()
        }
      }else if(props.pageType === PageType.Edit){
        const res2 = await $http?.postWaylinejobEdit({ ...formData })
        const { data } = res2
        if(data.code === 200){
          cancelModal()
        }
      }
    }).catch(err => {
      console.log("新建任务报错", err)
    })
  }
  
  const cancelModal = () => {
    //console.log("关闭弹框")
    formState.value = baseFormState
    formRef.value.resetFields()
    emits('success')
    closeModal();
  }

  </script>
  <style lang="less" scoped>
  /deep/.scroll-container {
    padding: 0;
  }

  .container{
    padding: 0 20px;
    height: 560px;
    .tabs-wrap{
      display: flex;
      &.disabled{
        cursor: not-allowed;
      }
      .tabs {
        flex-grow: 1;
        position: relative;
        width: 200px;
        height: 49px;
        display: flex;
        justify-content: center;
        align-items: center;
        margin-right: 15px;
        background: rgba(21,91,129,0.04);
        &:last-child{
          margin-right: 0;
        }
        .title-icon{
          width: 41px;
          height: 36px;
          margin-right: 5px;
        }
        .active-icon{
          width: 15px;
          height: 15px;
          position: absolute;
          right: 0px;
          bottom: 0px;
        }
        .title{
          font-size: 16px;
          font-family: PingFangSC-Medium, PingFang SC;
          font-weight: 500;
          color: #333333;
        }
        &.active{
          color: #0A7BB8;
          background: rgba(21,91,129,0.04);
          border-radius: 5px;
          border: 1px solid #0A7BB8;
        }
      }
    }
    .form{
      margin-top: 10px;
      width: 100%;
      height: 500px;
      .device-info{
        width: 405px;
        height: 204px;
        display: flex;
        align-items: center;
        background: #F8FBFD;
        border-radius: 4px;
        .left{
          width: 50%;
          height: 100%;
          display: flex;
          justify-content: center;
          align-items: center;
          img{
            width: 136px;
            height: 144px;
          }
        }
        .right{
          width: 50%;
          text-align: left;
          .title{
            width: 100%;
            height: 21px;
            font-size: 15px;
            font-family: PingFangSC-Semibold, PingFang SC;
            font-weight: 600;
            color: #333333;
            line-height: 21px;
          }
          .model{
            margin-top: 8px;
            width: 100%;
            height: 18px;
            font-size: 13px;
            font-family: PingFangSC-Regular, PingFang SC;
            font-weight: 400;
            color: #666666;
            line-height: 18px;
          }
          .call-info{
            margin-top: 11px;
            width: 100%;
            height: 18px;
            font-size: 13px;
            font-family: PingFangSC-Regular, PingFang SC;
            font-weight: 400;
            color: #333333;
            line-height: 18px;
          }

        }
      }
      .flyline{
        width: 449px;
        height: 330px;
      }

      .way-line-info{
        height: 100%;
        display: flex;
        justify-content: flex-end;
        align-items: flex-end;
      }
      
      #map-container{
        width: 440px;
        height: 339px;
      }
      .map-container{
        width: 440px;
        height: 339px;
        display: flex;
        justify-content: center;
        align-items: center;
        img{
          width: 100px;
          height: 90px;
        }
      }
      .second-mod{
        width: 100%;
        height: 22px;
        display: flex;
        justify-content: center;
        align-items: center;
        font-size: 16px;
        font-family: PingFangSC-Medium, PingFang SC;
        font-weight: 500;
        color: #333333;
        line-height: 22px;
        &.icon{
          width: 360px;
          .task-icon{
            width: 100%;
            height: 2px;
            border: 1px solid #EDEDED;
          }
        }
      }
      
      .weekDayWrap{
        width: 100%;
        display: flex;
        .weekDayItem{
          flex-grow: 1;
          display: flex;
          justify-content: center;
          align-items: center;
          border: 1px solid #BBCFDA;
          &.active{
            background: linear-gradient(315deg, #2C9AD6 0%, #167DB5 100%);
          }
        }
      }
    }
  }
  
  </style>
  <style lang="less">
    .add-job-modal-wrap {
      .ant-modal-content{
        .ant-modal-header{
          background: linear-gradient(135deg, #073451 0%, #0B4C68 100%);
          .jeecg-basic-title{
            color: #fff;
          }
        }
        .ant-modal-close-x{
          color: #fff;
        }
        .ant-modal-body{
          .ant-form-item.ant-form-item-with-help{
            margin-bottom: 36px !important;
          }
        }
      }
    }
  </style>